package org.xhl.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xhl
 * @Date 2023/12/14 13:47:12
 */
@Slf4j
public class NettyServer {


    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        log.info("正在启动");
        try {
            ServerBootstrap b = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG));

            b.childHandler(new ServerInitializer());

            ChannelFuture channelFuture = b.bind(8888);
            channelFuture.addListener(future -> {
                //异步操作，添加监听接口
                if (future.isSuccess()) {
                    log.info("服务端绑定接口成功");
                } else {
                    log.error("服务端绑定接口失败");
                }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
        log.info("关闭");
    }
}
